<template>
  <el-select
    v-model="input"
    :placeholder="itemConfig.placeholder"
    :disabled="itemConfig.disabled"
    @change="handleUpdate"
    style="width: 100%"
    :style="itemConfig.style"
  >
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
</template>

<script lang="ts" setup>
  import { ref, PropType, watch, toRefs } from 'vue';
  import { excempleAsyncSelect } from '../dataExcemple';
  import { AsyncSelectItem, OptionType } from '../common-form-type';
  import { Http } from '@/utils/http';

  const props = defineProps({
    itemConfig: {
      type: Object as PropType<AsyncSelectItem>,
      default: (): AsyncSelectItem => excempleAsyncSelect,
    },
    itemValue: {
      type: [Number, String, Boolean],
      default: '',
    },
  });

  const { itemConfig, itemValue } = toRefs(props);
  const input = ref(itemValue.value);
  const options = ref<OptionType[]>([]);

  watch(itemValue, (v) => {
    input.value = v;
  });

  watch(itemConfig, () => {
    initOptions();
  });

  const emit = defineEmits({
    update: null,
  });

  const initOptions = () => {
    Http.get(itemConfig.value.url).then((res: any) => {
      if (itemConfig.value.formatter) {
        options.value = res.map((item: any) => itemConfig.value.formatter && itemConfig.value.formatter(item));
      } else {
        options.value = res;
      }
    });
  };

  initOptions();
  const handleUpdate = () => {
    emit('update', { val: input.value, prop: itemConfig.value.prop });
  };
</script>
